package com.imagefinder;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.util.*;

import org.w3c.dom.*;
import org.xml.sax.InputSource;


import com.util.ServerConfigurationReader;





import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


public class YahooImageFinder implements ImageFinder{
	
	public LinkedHashMap<String, String> sendReceive(String skey,int GCount){
		String[] pictures=null;
		URL google=null;
		//ArrayList<String> temp=null;
		LinkedHashMap<String, String> temp=null;
	try{
		google=new URL("http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query="+skey+"&start="+(GCount*20+1)+"&results=20");
	}catch(MalformedURLException ex)
	{
		JOptionPane.showMessageDialog(null,"URL is not correct.....");
	}
	try{
		URLConnection googleConnection=null;
		
		try{
		    if(!ServerConfigurationReader.isDirect()){
		    	Map<String, String> proxyDetails=ServerConfigurationReader.getProxyDetails();
		    	Proxy prox=new Proxy(Proxy.Type.HTTP,new InetSocketAddress((String)proxyDetails.get("proxyaddress"),Integer.parseInt(proxyDetails.get("proxyport"))));
		    	googleConnection=google.openConnection(prox);
		    }
		    else{
		    	googleConnection=google.openConnection();
		    }
		    }catch(Exception e){
		    	System.out.println("Retrieveing proxy details failed....");
		    }
		//Proxy prox=new Proxy(Proxy.Type.HTTP,new InetSocketAddress("192.248.8.106",3128));
		//URLConnection googleConnection=google.openConnection(prox);
		///URLConnection googleConnection=google.openConnection();
		InputStream is=googleConnection.getInputStream();
	
		BufferedReader	inputBuffer=new BufferedReader(new InputStreamReader(is));
		String str=inputBuffer.readLine();
		String tempStr=str;
		String ttempStr="";
		String tuStr="";
		while(tempStr!=null){
			tuStr=ttempStr;
			tempStr=inputBuffer.readLine();
			
			if(tempStr==null)
				break;
			ttempStr=tempStr;
			str+=tuStr;
		}
		
		//pictures=displayPicData(str);
		temp=getPicData(xmlparser(str));
		/*pictures=new String[temp.size()];
		for(int i=0;i<temp.size();i++){
			pictures[i]=(String)temp.get(i);
		}*/
		inputBuffer.close();
			
	}catch(Exception ex){
		JOptionPane.showMessageDialog(null,"Error in getting results.....");
	}
	return temp;
	}
		

	public Document xmlparser(String str){
		DocumentBuilder docBuilder=null;
		Document doc=null;
		DocumentBuilderFactory docBuilderFac=DocumentBuilderFactory.newInstance();
		try{
			docBuilder=docBuilderFac.newDocumentBuilder();
		}
		catch(ParserConfigurationException pcex){
			JOptionPane.showMessageDialog(null,"Parser Configuration Exception.........."+pcex.getMessage());
		}
		try{
		doc=docBuilder.parse(new InputSource(new StringReader(str)));
		}catch(Exception ex){
			System.out.print("Error in parsing document.........."+ex.getMessage());
		}
		//System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
		return doc;

	}
	
	public LinkedHashMap<String, String> getPicData(Document doc) throws UnsupportedEncodingException{
		String[] xmlTags=new String[4];
		LinkedHashMap<String, String> urls=new LinkedHashMap<String, String>();
		xmlTags[0]="Url";
		xmlTags[1]="ClickUrl";
		xmlTags[2]="RefererUrl";
		xmlTags[3]="Thumbnail";
		ArrayList picData;
		ArrayList<String> urlList=null;
		//Document thumbDoc=xmlparser(str);
		NodeList resultList=doc.getElementsByTagName("Result");
		//picData=new ArrayList (resultList.getLength());
		urlList=new ArrayList (resultList.getLength());
		for(int i=0;i<resultList.getLength();i++){
			
			Element result=(Element)resultList.item(i);
			//ReceivedPicture pic=new ReceivedPicture();
			String referURL=null;
			String thumbURL=null;
			
			for(int j=0;j<4;j++){
				
				NodeList URL=result.getElementsByTagName(xmlTags[j]);
				Element eFirstLevel=(Element)URL.item(0);
				if(j==0)
					System.out.println("Level 1");
					//pic.url=eFirstLevel.getTextContent();
				else if(j==1)
					System.out.println("Level 2");
					//pic.clickUrl=eFirstLevel.getTextContent();
				else if(j==2){
						referURL=eFirstLevel.getTextContent();
						String referencrURL=URLDecoder.decode(referURL, "UTF-8");
				}
					//System.out.println("Level 3");
					//pic.referenceUrl=eFirstLevel.getTextContent();
				else
				{
					NodeList thumbnailAdd=eFirstLevel.getElementsByTagName("Url");
					Element eSecondlevel=(Element)thumbnailAdd.item(0);
					//pic.thumbnailUrl=eSecondlevel.getTextContent();]
					//System.out.println(eSecondlevel.getTextContent());
					//urlList.add(eSecondlevel.getTextContent());
					thumbURL=eSecondlevel.getTextContent();
					thumbURL= URLDecoder.decode(thumbURL, "UTF-8"); 
				}
				
				}
			urls.put(thumbURL, referURL);
			//picData.add(pic);
				
			}
			//return picData;
		//return urlList;
		return urls;
			
			//NodeList URL=result.getElementsByTagName("Url");
			//Element e=(Element)URL.item(0);
		
	}
		
	/*public String[] displayPicData(String urlString){
	Document doc=xmlparser(urlString);
	ArrayList picData=getPicData(doc);
	String[] ThumbUrl=new String[picData.size()];
	for(int i=0;i<picData.size();i++){
		//ReceivedPicture receivedpicture=(ReceivedPicture)picData.get(i);
		
		ThumbUrl[i]=(String)picData.get(i);
		
	}
	return ThumbUrl;
	
	}*/
	
	@Override
	public LinkedHashMap<String, String> getResults(String searchKey, int gCount) {
		// TODO Auto-generated method stub
		LinkedHashMap<String, String> results=null;
		YahooImageFinder cg=new YahooImageFinder();
		results=cg.sendReceive(searchKey,gCount);
		return results;
	}
	
	
	public static void main(String[] args){
		LinkedHashMap<String, String> results=null;
		YahooImageFinder cg=new YahooImageFinder();
		results=cg.sendReceive("dog",1);
	}
	
}
	

